"""
as download from www.recapthca.com
modified by Massimo Di Pierro
"""


class RECAPTCHA(INPUT):

    API_SSL_SERVER="https://api-secure.recaptcha.net"
    API_SERVER="http://api.recaptcha.net"
    VERIFY_SERVER="api-verify.recaptcha.net"

    def __init__(self,request,public_key='',private_key='',use_ssl=False,error=None):
        self.remote_addr=request.env.remote_addr
        self.public_key=public_key
        self.private_key=private_key
        self.use_ssl=use_ssl
        self.error=error
        self.components=[]
        self.attributes={}
    def rec_accepts(self,vars):    
        import urllib2, urllib
        recaptcha_challenge_field=vars.recaptcha_challenge_field,
        recaptcha_response_field=vars.recaptcha_response_field
        private_key=self.private_key
        remoteip=self.remote_addr
        if not (recaptcha_response_field and recaptcha_challenge_field and
           len (recaptcha_response_field) and len (recaptcha_challenge_field)):
            return RecaptchaResponse (is_valid = False, error_code = 'incorrect-captcha-sol')
        params = urllib.urlencode ({
            'privatekey': private_key,
            'remoteip' : remoteip,
            'challenge': recaptcha_challenge_field,
            'response' : recaptcha_response_field,
            })
        request = urllib2.Request (
            url = "http://%s/verify" % self.VERIFY_SERVER,
            data = params,
            headers = {
              "Content-type": "application/x-www-form-urlencoded",
              "User-agent": "reCAPTCHA Python"
            })
        httpresp = urllib2.urlopen (request)
        return_values = httpresp.read ().splitlines ();
        httpresp.close();
        return_code = return_values [0]
        if return_code=="true": return True
        self.errors['captcha']=return_values[1]
        return False
    def xml(self):
        public_key=self.public_key
        use_ssl=self.use_ssl,
        error_param = ''
        if self.error: error_param = '&error=%s' % self.error
        if use_ssl: server = self.API_SSL_SERVER
        else: server = self.API_SERVER
        return """<script type="text/javascript" src="%(ApiServer)s/challenge?k=%(PublicKey)s%(ErrorParam)s"></script>
<noscript>
<iframe src="%(ApiServer)s/noscript?k=%(PublicKey)s%(ErrorParam)s" height="300" width="500" frameborder="0"></iframe><br />
<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
<input type='hidden' name='recaptcha_response_field' value='manual_challenge' />
</noscript>
""" % {'ApiServer' : server,'PublicKey' : public_key,'ErrorParam' : error_param }